package 中国.珍林.AI.图片.分类.Servlet;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import 中国.易.工具.Http工具;
import 中国.易.工具.Servlet工具;

import java.io.File;
import java.io.IOException;

@Log4j2
@WebServlet(urlPatterns = "/缩略图")
public class 缩略图 extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
    {
        String 路径 = req.getParameter("路径");
        int 大小 = Servlet工具.获取url参数4int(req, "s", 220, log);
        if (StringUtils.isBlank(路径))
        {
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        File f = new File(路径);
        if (!f.exists())
        {
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        if (f.isDirectory())
        {
            resp.sendRedirect("../" + Http工具.路径encode("文件夹.png"));
            return;
        }
        String 文件名 = f.getName();
        String[] ss = 文件名.split("\\.");
        if (ss.length < 2)
        {
            resp.sendRedirect("../" + Http工具.路径encode("文件.png"));
            return;
        }
        String 后缀 = ss[ss.length - 1].toLowerCase();
        if (!"jpg".equals(后缀) && !"jpeg".equals(后缀) && !"png".equals(后缀))
        {
            resp.sendRedirect("../" + Http工具.路径encode("文件.png"));
            return;
        }

        // 设置响应头部
        resp.setContentType("image/jpg"); // 根据图片类型设置MIME类型
        resp.setHeader("Content-Disposition",
                "inline; filename=\"" + Http工具.路径encode(f.getName()) + "\""); // 可选：设置文件名以便下载

        Thumbnails.of(f).size(大小, 大小).outputFormat("jpg").toOutputStream(resp.getOutputStream());
    }
}
